package com.antoco.operation.bigscreen.config;

import com.antoco.operation.bigscreen.utils.SystemUtil;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 频道配置类
 * @author johnsonpei
 */
@Component
@ConfigurationProperties(prefix="ws")
public class ChannelConfig {
    @Getter
    @Setter
    private Map<String, String> channels;

    @Autowired
    private SystemUtil systemUtil;

    private Map<String, Map<String, String>> channelsTableInfo = null;

    /**
     * 根据频道名获取所有表名
     *
     * @param channelName
     * @return
     */
    public Map<String, String> getChannelTables(String channelName) {
        if (channelsTableInfo == null) {
            channelsTableInfo = new ConcurrentHashMap<>(0);
        }

        if (channels.containsKey(channelName)) {
            if (!channelsTableInfo.containsKey(channelName)) {
                Map<String, String> tablesMap = new ConcurrentHashMap<>(10);
                String[] tables = channels.get(channelName).split(",");
                systemUtil.printDebug("tablesStr:" + channels.get(channelName));
                systemUtil.printDebug("tables:" + tables.toString());
                for (String table : tables) {
                    table = table.trim();
                    tablesMap.put(table, table);
                }

                channelsTableInfo.put(channelName, tablesMap);
            }

            return channelsTableInfo.get(channelName);
        } else {
            return new ConcurrentHashMap<>(0);
        }
    }

    /**
     * 通过表明获取频道名
     *
     * @param tableName
     * @return List<String> 所属频道列表
     */
    public List<String> getChannelNameByTableName(String tableName) {
        List<String> channelNames = new ArrayList<String>(5);

        for (String channelName : channels.keySet()) {
            Map<String, String> tablesMap = getChannelTables(channelName);
            if (tablesMap.containsKey(tableName)) {
                channelNames.add(channelName);
            }
        }
        return channelNames;
    }
}
